package ui.panel;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import exceptions.AuthenticationFailedException;

import bl.BL_Autentifizierung;

import tools.Session;
import ui.Mainframe;

/**
 * Login panel
 * @author Martin Schophaus
 */
@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
        /**
         * Inline Class
         * Listener for the button
         * @author Martin Schophaus
         */
        private class AEL implements ActionListener {

        	LoginPanel panel;
                
                public AEL (LoginPanel panel) {
                        this.panel = panel;
                }
                
                @Override
                public void actionPerformed(ActionEvent arg0) {
                        if(arg0.getActionCommand().equals("openConn")) {
                                this.panel.authenticate();
                        }
                }
                
        }
        
        private JTextField user = new JTextField("test@epad.de");
        private JPasswordField password = new JPasswordField("epad");
        private JButton anmelden = new JButton("Anmelden");
        private Mainframe frame;
        
        public LoginPanel(Mainframe frame) {
                this.frame = frame;
                this.setLayout(new GridLayout(3, 2));
                //this.anmelden.addActionListener(new AEL(this));
                this.anmelden.setActionCommand("openConn");
                
                this.add(new JLabel("Username"));
                this.add(this.user);
                this.add(new JLabel("Password"));
                this.add(this.password);
                this.add(this.anmelden);
                this.anmelden.addActionListener(new AEL(this));
                        
        }
        
        public void authenticate() {
        	BL_Autentifizierung bl = new BL_Autentifizierung();
        	
        	
        	
        	try {
        		bl.authenticate(this.user.getText(), String.valueOf(this.password.getPassword()));
        		
        	} catch (AuthenticationFailedException ex) {
        		JOptionPane.showMessageDialog(this, "Ihre Anmeldedaten sind falsch. Bitte erneut versuchen.");
        		return;
        	}
        	if(Session.email != null) {
        		this.frame.menuBarSetEnabled(true);
        		JOptionPane.showMessageDialog(this, "Erfolgreich Angemeldet.");
        	}
        	
        }
}

